package com.rzico.sbl.ui.member

import androidx.core.view.isVisible
import com.amap.api.services.core.PoiItem
import com.jeremyliao.liveeventbus.LiveEventBus
import com.lzg.extend.jackson.JsonUtil
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityMemberAdressEditBinding
import com.rzico.sbl.model.AddressData
import com.rzico.sbl.model.BaseUrl
import com.rzico.sbl.model.RegionBean
import com.rzico.sbl.other.showAreaDialog
import com.rzico.sbl.ui.manual.ManualEditActivity
import com.rzico.sbl.viewmodel.AddressViewModel
import com.xinnuo.common.extend.*
import com.xinnuo.common.helper.*
import com.xinnuo.common.other.DecimalNumberFilter
import com.xinnuo.common.other.NameLengthFilter
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.common_ui.utils.bindLifeCycle
import com.xinnuo.common_ui.utils.clear
import com.xinnuo.common_ui.utils.setCompoundDrawable
import com.xinnuo.common_ui.utils.showListDialog
import com.xinnuo.common_ui.utils.subscribeBySuccess

class MemberAdressEditActivity : BaseActivity(R.layout.activity_member_adress_edit) {

    private val mBinding by lazy {
        ActivityMemberAdressEditBinding.bind(getRootView())
    }

    private val mAreaList = ArrayList<RegionBean>()
    private var mLat = 0.0
    private var mLng = 0.0
    private var mLevel = -1
    private var mAreaId = ""
    private var mAreaCode = ""
    private var mMemberId = ""
    private var mAdressId = ""

    override fun getViewModel() = get<AddressViewModel>()

    override fun initData() {
        initTitle(title = "收货地址")

        if (mMemberId.isEmpty() && mAdressId.isEmpty()) {
            tvTitle?.text = "添加会员"
        }
    }

    override fun initListener() {
        mBinding.apply {
            adressName.filters = arrayOf(NameLengthFilter(20))
            adressFee.filters = arrayOf(DecimalNumberFilter(), NameLengthFilter(8))
            adressDefault.setCompoundDrawable(
                rightDrawable = R.drawable.address_default_selector,
                rightSize = 15f
            )

            mMemberId = intent.getExtra("memberId")
            intent.getExtra("memberPhone")
                .notEmpty {
                    adressPhone.setText(this)
                }

            // 编辑会员地址
            setAddressData(intent.getParcelableExtra("bean"))

            // 省市区选择
            adressArea.oneClick {
                mAreaList
                    .isNotEmpty()
                    .conditionElse(
                        actionTrue = ::showBottomArea,
                        actionFalse = {
                            getViewModel()
                                .getAreaList {
                                    mAreaList.addItems(it)

                                    showBottomArea()
                                }
                        }
                    )
            }

            adressAreaMap.oneClick {
                startActivityEx<MemberAdressAddActivity>("from" to "edit")
            }

            adressFloorLl.oneClick {
                val items = arrayListOf(
                    "有电梯", "1层", "2层", "3层", "4层", "5层", "6层", "7层", "8层", "9层"
                )

                showListDialog(
                    title = "请选择楼层",
                    items = items,
                    index = items.indexOf(adressFloor.content),
                    listener = { index, hint ->
                        mLevel = index
                        adressFloor.text = hint
                    }
                )
            }

            btManual.oneClick {
                submitInfo(true)
            }

            btSave.oneClick {
                submitInfo(false)
            }

            LiveEventBus
                .get("adressAdd", PoiItem::class.java)
                .observe(getLifecycleOwner()) {
                    setData(it)
                }
        }
    }

    private fun submitInfo(isManual: Boolean) {
        mBinding.apply {
            when {
                adressName.text.isBlank() -> {
                    adressName.requestFocus()
                    showToast("请输入用户姓名")
                    return
                }

                adressPhone.text.isEmpty() -> {
                    adressPhone.requestFocus()
                    showToast("请输入联系电话")
                    return
                }

                !adressPhone.text.isTel()
                        && !adressPhone.text.isVirtual() -> {
                    adressPhone.requestFocus()
                    showToast("请输入正确的联系方式")
                    return
                }

                adressDetail.text.isBlank() -> {
                    adressDetail.requestFocus()
                    showToast("请输入详细地址")
                    return
                }

                mLevel < 0 -> {
                    showToast("请选择用户楼层")
                    return
                }
            }

            if (mMemberId.isEmpty()
                && mAdressId.isEmpty()
            ) {
                getViewModel()
                    .adressAdd(
                        BaseUrl.adressAdd,
                        "areaId" to mAreaId,
                        "areaCode" to mAreaCode,
                        "lat" to mLat,
                        "lng" to mLng,
                        "consignee" to adressName.textTrim,
                        "phone" to adressPhone.content,
                        "address" to adressDetail.textTrim,
                        "level" to mLevel,
                        "levelFreight" to "0",
                        "isDefault" to adressDefault.isChecked,
                    )
                    .bindLifeCycle(getLifecycleOwner())
                    .subscribeBySuccess(
                        event = getViewModel(),
                        onSuccess = { result ->
                            showToast("添加会员成功！")

                            JsonUtil.jsonToBean(
                                result,
                                AddressData::class.java
                            )?.let {
                                isManual.condition {
                                    startActivityEx<ManualEditActivity>(
                                        "receiverId" to it.id,
                                        "cardId" to it.cardId,
                                        "memberId" to it.memberId,
                                        "consignee" to it.consignee,
                                        "phone" to it.phone,
                                        "address" to it.address
                                    )
                                }
                            }

                            // 更新会员列表
                            LiveEventBus
                                .get("memberList")
                                .post("refresh")

                            finishView()
                        }
                    )
            } else {
                getViewModel()
                    .adressAdd(
                        conditionIf(
                            mMemberId.isNotEmpty(),
                            BaseUrl.adressAdd,
                            BaseUrl.adressUpdate
                        ),
                        "id" to mAdressId,
                        "memberId" to mMemberId,
                        "areaId" to mAreaId,
                        "areaCode" to mAreaCode,
                        "lat" to mLat,
                        "lng" to mLng,
                        "consignee" to adressName.textTrim,
                        "phone" to adressPhone.content,
                        "address" to adressDetail.textTrim,
                        "level" to mLevel,
                        "levelFreight" to adressFee.textOrEmpty("0"),
                        "isDefault" to adressDefault.isChecked,
                    )
                    .bindLifeCycle(getLifecycleOwner())
                    .subscribeBySuccess(
                        event = getViewModel(),
                        onSuccess = { result ->
                            showToast("地址保存成功！")

                            JsonUtil.jsonToBean(
                                result,
                                AddressData::class.java
                            )?.let {
                                isManual.condition {
                                    startActivityEx<ManualEditActivity>(
                                        "receiverId" to it.id,
                                        "cardId" to it.cardId,
                                        "memberId" to it.memberId,
                                        "consignee" to it.consignee,
                                        "phone" to it.phone,
                                        "address" to it.address
                                    )
                                }

                                // 更新会员列表
                                it.default
                                    .condition {
                                        LiveEventBus
                                            .get("memberList")
                                            .post("refresh")
                                    }
                            }

                            // 更新地址列表
                            LiveEventBus
                                .get("addressList")
                                .post("refresh")

                            finishView()
                        }
                    )
            }
        }
    }

    /**
     * 省市区弹框
     */
    private fun showBottomArea() {
        showAreaDialog(
            title = "请选择地区",
            list = mAreaList,
            listener = { pname, cname, aname, _, _, adcode ->
                mBinding.apply {
                    mLat = 0.0
                    mLng = 0.0
                    mAreaId = ""
                    mAreaCode = adcode

                    adressArea.text = "$pname $cname $aname"
                    adressDetail.clear()
                }
            }
        )
    }

    private fun setData(item: PoiItem?) {
        item?.let {
            mLat = it.latLonPoint.latitude
            mLng = it.latLonPoint.longitude
            mAreaId = ""
            mAreaCode = it.adCode

            mBinding.adressDetail.setText(it.snippet + it.title)
            mBinding.adressArea.text = "${it.provinceName} ${it.cityName} ${it.adName}"
        }
    }

    private fun setAddressData(item: AddressData?) {
        item?.let { bean ->
            mLat = bean.lat.doubleValue
            mLng = bean.lng.doubleValue
            mLevel = bean.level.intValue
            mAreaId = bean.areaId
            mAdressId = bean.id

            mBinding.apply {
                adressName.setText(bean.consignee)
                adressPhone.setText(bean.phone)

                adressArea.text = bean.areaName
                adressDetail.setText(bean.address)

                adressFloor.text = when (mLevel) {
                    0 -> "有电梯"
                    else -> "${mLevel}层"
                }

                adressFeeLl.isVisible = mMemberId.isEmpty()
                bean.levelFreight
                    .also {
                        if (it.doubleValue > 0) adressFee.setText(it)
                    }

                adressDefault.isChecked = bean.default
            }
        }
    }

}